<?php
// <standard:for var="EXPRESSION" value="VARNAME" start="EXPRESSION|INTEGER" end="EXPRESSION|INTEGER" step="INTEGER">BODY</standard:for>
class StandardForTag extends AbstractTag {
	public function parseStartTag($tblParameters=array()) {
		$this->checkParameters($tblParameters, array("value"));
		if(isset($tblParameters['var']) && !$this->isExpression($tblParameters['var'])) throw new ViewException("Value 'var' must be an expression for ".get_class($this)."!");
		return '<?php for($'.$tblParameters['value'].'='.(isset($tblParameters['start'])?$this->parseCounter($tblParameters['start']):0)
		.'; $'.$tblParameters['value'].'<'.(isset($tblParameters['end'])?'='.$this->parseCounter($tblParameters['end']):'sizeof('.$this->parseExpression($tblParameters['var']).')')
		.'; $'.$tblParameters['value'].(isset($tblParameters['step'])?"+=".$tblParameters['step']:"++").') { ?>';
	}
	
	public function parseEndTag() {
		return '<?php } ?>';
	}
	
	protected function checkParameters($tblParameters, $tblRequiredParameters) {
		parent::checkParameters($tblParameters, $tblRequiredParameters);
		if(!isset($tblParameters['end']) && !isset($tblParameters['var'])) throw new ViewException("You must define either 'end' or 'var' attributes for ".get_class($this)."!");
	}
	
	private function parseCounter($strExpression) {
		if(is_numeric($strExpression)) 					return $strExpression;
		else if(!$this->isExpression($strExpression)) 	return '$'.$strExpression;
		else 											return $this->parseExpression($strExpression);
	}
}